package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 国际长途全程要求完成时间
 */
@Service
public class GJWholeRequireFinishTimeAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
        String defaultValue = LocalAttrUtils.wholeOffsetDay(30);
        if(KiteStringUtils.isEmpty(commonAttr.getDefaultValue())){
            String BIZ_TYPE = querySceneInstService.getExtParameterValue(sceneInstId,"serviceOfferId");
            String nowFinishTime = null;
            if (KiteStringUtils.equalsAny(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK,sceneInst.getServiceOfferId(),BIZ_TYPE)) {
                nowFinishTime = LocalAttrUtils.getInstance().wholeOffsetDayOB(prodInst.getSpecId(), null,LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK);
            }else{
                nowFinishTime = LocalAttrUtils.getInstance().wholeOffsetDay(prodInst.getSpecId(), null);
            }
            String value = LocalAttrUtils.compareDate(commonAttr, nowFinishTime);
            commonAttr.setValue(value);
            commonAttr.setValueDesc(value);
            commonAttr.setDefaultValue(value);
            attr.setValue(value);
            attr.setValueDesc(value);
            attr.setDefaultValue(value);
            //保存defaultvalue
            operateSceneCommonService.setCommonAttr(sceneInstId, attr);
        }
}

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteAttr finishTime = querySceneInstService
            .getCommonAttr(sceneInstId, fieldName);
        if(null==finishTime.getDefaultValue()){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        if (KiteStringUtils.isEmpty(value)){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        if(value.equals(finishTime.getDefaultValue())){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        String completeTimePattern = LocalAttrUtils.FormatByValue(value);
        Date complateDate = null;
        Date initDate = null;
        try{
            complateDate = DateUtils.parseStrToDate(value, completeTimePattern);
            if(KiteStringUtils.isNotEmpty(finishTime.getDefaultValue())){
                initDate = DateUtils.parseStrToDate(finishTime.getDefaultValue(), completeTimePattern);
            }
        }catch (Exception e){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
        }
        if(Objects.nonNull(initDate)){
            if (null != complateDate && DateUtil.compare(initDate,complateDate) >1){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于当前时间:"+finishTime.getDefaultValue());
            }
        }
        if (null != complateDate && null!=finishTime && DateFormatUtils.compareDate(value, DateUtils.getDateTimeString(), completeTimePattern) < 0){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于当前时间:"+DateUtils.getDateTimeString());
        }
/*        if(finishTime!=null&&KiteStringUtils.isNotEmpty(finishTime.getDefaultValue())&&DateFormatUtils.compareDate(value, DateUtils.getDateTimeString(), DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于当前时间:"+DateUtils.getDateTimeString());
        }*/
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public String compareDate(CommonAttrVO commonAttr,KiteProdInst prodInst){
        String nowFinishTime = LocalAttrUtils.getInstance().wholeOffsetDay(prodInst.getSpecId(), null);
        String origin = commonAttr.getOriginValue();
        if(null==origin){
            origin=commonAttr.getOldValue();
        }
        if(DateFormatUtils.compareDate(origin, nowFinishTime, DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            return nowFinishTime;
        }else{
            return origin;
        }
    }
    public void checkTime(String type, KiteAttr ...attr) {
        if (Objects.isNull(attr)) {
            return;
        }
        List<KiteAttr> kiteAttrList = Arrays.asList(attr);
        if (KiteListUtils.isNotEmpty(kiteAttrList)) {
            kiteAttrList.forEach(kiteAttr -> {
                String currDate = kiteAttr.getValue();
                String originDate = kiteAttr.getOriginValue();
                // 如果加急，不能晚于之前的完成时间
                if ("URGENT".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, DateFormatUtils.DATE_MINUTE_FORMAT) > 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","加急，要求完成时间不能晚于之前的完成时间");
                    }
                }
                // 如果是延期，不能早于之前的完成时间
                if ("POSTPONE".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, DateFormatUtils.DATE_MINUTE_FORMAT) < 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","延期，要求完成时间不能早于之前的完成时间");
                    }
                }
                // 校验全程要求完成时间早于当前时间
                if ("ORD10012".equals(kiteAttr.getFieldName()) && (DateFormatUtils.compareDate(currDate, DateUtils.getDateTimeString(), DateFormatUtils.DATE_MINUTE_FORMAT) < 0)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","全程要求完成时间不能小于当前时间");
                }
            });
        }
    }
}
